package com.aoxin.controller.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.aoxin.util.ErrorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.aoxin.mapper.SlfChildExpectedTimeMapper;
import com.aoxin.mapper.course.systemCourse.SchoolCoursePageDao;
import com.aoxin.mapper.course.webCourse.MyCoursePageMapper;
import com.aoxin.model.course.SchoolCoursePage;
import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.course.SlfMyCoursePage;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.course.webCourse.ChildrenService;
import com.aoxin.service.inter.course.webCourse.MyCoursePageService;
import com.aoxin.service.inter.course.webCourse.MyCourseService;
import com.aoxin.service.inter.opm.UserService;
import com.aoxin.util.AjaxRes;
import com.aoxin.util.Const;
import com.aoxin.util.ThreadLocalUtil;
import com.aoxin.util.enumerate.OperateType;
import com.aoxin.util.enumerate.UserType;
import com.aoxin.util.log.LogInfo;

import net.sf.json.JSONObject;

@RestController
@ResponseBody
@RequestMapping("/web/myCenter/")
public class MyCenterController {
private Logger logger = LoggerFactory.getLogger(MyCenterController.class);

    @Autowired
    UserService userService;

    @Autowired
    MyCourseService myCourseService;

    @Autowired
    MyCoursePageService myCoursePageService;

    @Autowired
    ChildrenService childrenService;
    
    @Autowired
    SchoolCoursePageDao schoolCoursePageDao;
    
    @Autowired
    MyCoursePageMapper myCoursePageDao;
    
    @Autowired
    SlfChildExpectedTimeMapper slfChildExpectedTimeMapper;



    /**
     * 获取用户基本信息
     *
     * @param res
     * @return
     */
    @RequestMapping("getUserInfo")
    @LogInfo(content = "个人中心我的基本信息", operateType = OperateType.QUERY, userType = UserType.USER)
    public AjaxRes getUserInfo(AjaxRes res) {
        SlfUser slfUser = ThreadLocalUtil.getUser();
        Integer userId = slfUser.getUserId();
        SlfUser user = userService.getUser(userId);
        try {
            res.setSucceed(user, "getUserInfo success!");
        } catch (Exception e) {
            res.setFailMsg(e.getMessage());
        }
        return res;
    }

    /**
     * 修改用户基本信息
     * @param slfUser
     * @param res
     * @return
     */
    @RequestMapping("updateUserInfo")
    public AjaxRes updateUserInfo(SlfUser slfUser, AjaxRes res) {
        if(slfUser.getUserId()==null){
            slfUser.setUserId(ThreadLocalUtil.getUser().getUserId());
        }
        try {
            if (slfUser!=null&&slfUser.getUserId()!=null&&slfUser.getUserId()!=0) {
                Integer result = userService.updateUserInfo(slfUser);
                if (result == 2) {
                    res.setSucceedMsg(ErrorUtil.USER_FIRST_SUCCESS);
                } else if(result>0){
                    res.setSucceedMsg(ErrorUtil.USER_ADDR_SUCCESS);
                }else{
                    res.setFailMsg(ErrorUtil.USER_ADDR_FAILURED);
                }
            } else {
                logger.info("修改用户基本信息获取用户ID失败");
                res.setFailMsg(ErrorUtil.USER_ADDR_ERROR);
            }
        } catch (IllegalAccessException e) {
            res.setFailMsg(e.getMessage());
        }
        return res;
    }

    /**
     * 查询用户的孩子课程
     *
     * @param request
     * @return
     */
    @RequestMapping("getUserChildrenCourse")
    @LogInfo(content = "个人中心孩子课程", operateType = OperateType.QUERY, userType = UserType.USER)
    public AjaxRes getUserChildrenCourse(AjaxRes ajaxRes, HttpServletRequest request,String type,Integer children) {
    	try{
        List<SlfChildren> childrenCourse = new ArrayList<SlfChildren>();
        Map<String,Object> map = new HashMap<String, Object>();
        //0显示所有,1显示默认
        if(type!=null && !"".equals(type)){
        if(type.equals("0")){
            Integer userId = ThreadLocalUtil.getUser().getUserId();
       // 	Integer userId = 230;
            List<Integer> childrenIdList = childrenService.getChildrenId(userId);
            for (Integer childrenId : childrenIdList) {
            	SlfChildren slfChildren = childrenService.getAChildren(childrenId);
            	map.put("childrenId",childrenId);
                //C类
                List<SchoolCoursePage> SchoolCoursePage = schoolCoursePageDao.getChildrenMyCourseAll(map);
                //B类
                List<SlfMyCoursePage> slfMyCoursePageList = myCoursePageDao.getChildrenCoursePageCount(childrenId);
                slfChildren.setSchoolCoursePage(SchoolCoursePage);
                slfChildren.setChildrenCoursePage(slfMyCoursePageList);
                childrenCourse.add(slfChildren);
            }
            ajaxRes.setSucceed(childrenCourse,Const.DATA_SUCCEED);
        }else{
            map.put("childrenId",children);
            SlfChildren slfChildren = childrenService.getAChildren(children);
            //C类
            List<SchoolCoursePage> SchoolCoursePage = schoolCoursePageDao.getChildrenMyCourseAll(map);
            //B类
            List<SlfMyCoursePage> getChildrenCoursePageCount = myCoursePageDao.getChildrenCoursePageCount(children); 
            slfChildren.setSchoolCoursePage(SchoolCoursePage);
            slfChildren.setChildrenCoursePage(getChildrenCoursePageCount);
            childrenCourse.add(slfChildren);
			ajaxRes.setSucceed(childrenCourse,Const.DATA_SUCCEED);
          }
         }else{
        	 //购买的时候做出判断是否
        	 Integer userId = ThreadLocalUtil.getUser().getUserId();
        	 Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
        	 map.put("childrenId",childrenId);
             SlfChildren slfChildren = childrenService.getAChildren(childrenId);
             Integer a = slfChildExpectedTimeMapper.IsExpectedTime(childrenId);
        	 if(a == 0){
        	 slfChildren.setState(0);
        	 }else{
        	 slfChildren.setState(1);
        	 }
             //C类
             List<SchoolCoursePage> SchoolCoursePage = schoolCoursePageDao.getChildrenMyCourseAll(map);
             //B类
             List<SlfMyCoursePage> getChildrenCoursePageCount = myCoursePageDao.getChildrenCoursePageCount(childrenId); 
             slfChildren.setSchoolCoursePage(SchoolCoursePage);
             slfChildren.setChildrenCoursePage(getChildrenCoursePageCount);
             childrenCourse.add(slfChildren);
 			ajaxRes.setSucceed(childrenCourse,Const.DATA_SUCCEED);
         }
		}catch (Exception e) {
			ajaxRes.setFailMsg(e.getMessage());
		}
        return ajaxRes;
       }

    /**
     * 查询用户孩子信息
     * @param res
     * @return
     */
    @RequestMapping("getChildrenInfo")
    @LogInfo(content = "个人中心孩子信息", operateType = OperateType.QUERY, userType = UserType.USER)
    public AjaxRes getChildrenInfo(AjaxRes res) {
        SlfUser slfUser = ThreadLocalUtil.getUser();
        Integer userId = slfUser.getUserId();
        if (userId != null) {
            List<SlfChildren> slfChildrenList = childrenService.getChildrenInfo(userId);
            res.setSucceed(slfChildrenList, "getChildrenInfo success!");
        } else {
            res.setFailMsg("userId is null");
        }
        return res;
    }


    /**
     * 修改孩子校区
     * @param res
     * @param jsonObject
     * @return
     */
    @RequestMapping("updateChildrenSchool")
    @LogInfo(content = "个人中心孩子校区", operateType = OperateType.UPDATE, userType = UserType.USER)
    public AjaxRes updateChildrenSchool(AjaxRes res, @RequestBody JSONObject jsonObject) {
        if (jsonObject != null&&jsonObject.size()!=0) {
            Integer childrenId=Integer.valueOf(jsonObject.get("childrenId").toString());
            String schoolName=jsonObject.get("schoolName").toString();
            System.err.println("childrenId"+childrenId+"schoolName:"+schoolName);
            if (schoolName != null && !"".equals(schoolName)) {
                Integer result = childrenService.updateChildrenSchool(childrenId, schoolName);
                if (result != 0) {
                    res.setSucceed("updateChildrenSchool success!");
                } else {
                    res.setFailMsg("updateChildrenSchool Fail!");
                }
            } else {
                res.setFailMsg("schoolName is null");
            }
        } else {
            res.setFailMsg("childrenId is null");
        }
        return res;
    }


    /**
     * 充值立方币
     * @param lfb
     * @param res
     * @return
     */
    @RequestMapping("rechargeLfb")
    @LogInfo(content = "个人中心充值立方币", operateType = OperateType.UPDATE, userType = UserType.USER)
    public AjaxRes rechargeLfb(Double lfb, AjaxRes res) {
        SlfUser slfUser = ThreadLocalUtil.getUser();
        Integer userId = slfUser.getUserId();
        Integer result = userService.rechargeLfb(lfb, userId);
        if (result != 0) {
            res.setSucceed("rechargeLfb success!");
        } else {
            res.setFailMsg("rechargeLfb Fail!");
        }
        return res;
    }
    
    
    /**
     * 查询我的孩子课程
     * @param childrenId
     * @param res
     * @return
     */
    @RequestMapping("getMyChildrenCoursePage")
    public AjaxRes getMyChildrenCoursePage(Integer  childrenId, AjaxRes res,String type) {
    	try {
    		   List<SlfChildren> childrenCourse = new ArrayList<SlfChildren>();
    		if("Y".equals(type)){
    			//Y 查询所有孩子课程包
    			Integer userId = ThreadLocalUtil.getUser().getUserId();
    	            List<Integer> childrenIdList = childrenService.getChildrenId(userId);
    	            for (Integer childrenid : childrenIdList) {
    	                SlfChildren slfChildren = childrenService.getAChildren(childrenid);
    	                List<Map<String,Object>> slfMyCoursePageList = myCourseService.queryMyChildrencoursePage(childrenid);
    	                slfChildren.setMyChildrenCoursePage(slfMyCoursePageList);
    	                childrenCourse.add(slfChildren);
    	            }
    		}else{
    			//N 查询单个孩子课程包
    			   SlfChildren slfChildren = childrenService.getAChildren(childrenId);
    			   List<Map<String,Object>> slfMyCoursePageList = myCourseService.queryMyChildrencoursePage(childrenId);
    			   slfChildren.setMyChildrenCoursePage(slfMyCoursePageList);
    			   childrenCourse.add(slfChildren);
    		}
    		res.setSucceed(childrenCourse, Const.DATA_SUCCEED);
    	
		} catch (Exception e) {
			res.setFailMsg(e.getMessage());
		}
        return res;
    }
    @RequestMapping("getSurplusClassHour")
    public AjaxRes getSurplusClassHour(AjaxRes res) {
    	try {
       List<SlfChildren> surplusClassHourList=childrenService.surplusClassHour();
       	res.setSucceed(surplusClassHourList,Const.DATA_SUCCEED);
		} catch (Exception e) {
			res.setFailMsg(e.getMessage());
		}
    	return res;
    }
}
